<template>
  <el-dialog
    title="导入系统词库"
    :visible.sync="visible"
    width="40%"
    :before-close="handleBeforeClose"
    :close-on-click-modal="false"
    class="word-dialog"
  >
    <!-- 模板下载 -->
    <div class="template-download">
      <el-link type="primary" @click="downloadTemplate">下载导入模板</el-link>
    </div>

    <!-- 上传组件 -->
    <el-upload
      ref="uploader"
      class="file-uploader"
      :action="uploadFileAction"
      :headers="uploadHeaders"
      :show-file-list="true"
      :before-upload="beforeFileUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-progress="handleUploadProgress"
      :limit="1"
      :data="extraData"
    >
      <el-button type="primary" :disabled="uploading">点击上传文件</el-button>
      <div slot="tip" class="el-upload__tip">
        仅支持 CSV 或 Excel 文件，大小不超过 20MB
      </div>
      <div slot="tip" class="el-upload__tip">
        注意：上传文件的文件名即词库名称
      </div>
    </el-upload>

    <!-- 上传进度条 -->
    <div v-if="uploading" class="upload-progress">
      <el-progress :percentage="progressPercent" status="active"></el-progress>
    </div>
  </el-dialog>
</template>

<script>

import { getToken } from '@/utils/auth'

export default {
  name: 'WordDialog',
  props: {
    value: Boolean,
    attribution: {
      type: String,
      required: true
    },
    // eslint-disable-next-line vue/require-default-prop
    stuId: {
      type: String,
      required: false
    },
    parentId: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      visible: this.value,
      uploadFileAction: `${process.env.VUE_APP_BASE_API}/wordSystemLibraryType/word/import`,
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      uploading: false, // 是否上传中
      progressPercent: 0, // 上传进度
      extraData: {
        parentId: this.parentId
      }
    }
  },
  watch: {
    value(val) {
      this.visible = val
      if (val && this.libId) {
        this.pageBean.pageNum = 1
        this.getTableData()
      }
    },
    visible(val) {
      this.$emit('input', val)
    }
  },
  created() {
  },
  methods: {
    handleClose() {
      if (this.uploading) {
        this.$notify.warning({
          title: '操作受限',
          message: '文件上传中，请稍候完成后再关闭！',
          showClose: false
        })
        return
      }
      this.innerVisible = false
    },
    downloadTemplate() {
      const link = document.createElement('a')
      link.href = process.env.BASE_URL + 'template/单词导入模板.csv'
      link.setAttribute('download', '单词导入模板.csv')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    beforeFileUpload(file) {
      const isCSV = file.type === 'text/csv'
      const isExcel =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!(isCSV || isExcel)) {
        this.$notify.error({
          title: '错误的格式',
          message: '仅支持上传 CSV 或 Excel 文件！',
          showClose: false
        })
        return false
      }
      if (!isLt20M) {
        this.$notify.error({
          title: '文件过大',
          message: '上传文件不能超过 20MB！',
          showClose: false
        })
        return false
      }
      return true
    },
    handleUploadProgress(event) {
      this.uploading = true
      this.progressPercent = Math.floor(event.percent)
    },
    handleUploadSuccess(res) {
      this.uploading = false
      this.progressPercent = 100
      if (res.success) {
        this.$notify.success({
          title: '上传成功',
          message: '文件导入成功！',
          showClose: false
        })
        this.$emit('uploaded') // 通知父组件刷新数据
        setTimeout(() => this.handleClose(), 500)
      } else {
        this.$notify.error({
          title: '上传失败',
          message: res.message || '文件导入失败！',
          showClose: false
        })
      }
    },
    handleUploadError() {
      this.uploading = false
      this.progressPercent = 0
      this.$notify.error({
        title: '上传失败',
        message: '服务器异常，请稍后再试！',
        showClose: false
      })
    },
    handleBeforeClose(done) {
      done()
    }
  }
}
</script>

<style scoped>
.template-download {
  margin-bottom: 15px;
}

.file-uploader {
  display: block;
  text-align: center;
}

.upload-progress {
  margin-top: 20px;
}
</style>
